package com.learning.spring.ioc.bean.lifecycle.entity;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.Date;
import java.util.StringJoiner;

/**
 * ClassName: User
 * Description: 实体类
 * Date: 2020/7/22 9:52 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Setter
@Getter
public class User implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean {
    private int id;
    private String name;
    private int age;
    private Date createTime;

    public User() {
        System.out.println("调用 User 构造函数，开始被实例化");
    }

    public void setName(String name) {
        System.out.println("调用设置 Name 属性的 setName 方法");
        this.name = name;
    }

    /**
     * BeanFactoryAware 接口方法
     *
     * @param beanFactory
     * @throws BeansException
     */
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("调用 BeanFactoryAware.setBeanFactory() 方法，将 BeanFactory 容器实例设置到 Bean 中");
    }

    /**
     * BeanNameAware 接口方法
     *
     * @param name
     */
    @Override
    public void setBeanName(String name) {
        System.out.println("调用 BeanNameAware.setBeanName() 方法，将配置文件中该 Bean 对应的名称设置进来");
    }

    /**
     * InitializingBean 接口方法
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("调用 InitializingBean.afterPropertiesSet() 方法，完成 Bean 的初始化");
    }

    /**
     * DisposableBean 接口方法
     *
     * @throws Exception
     */
    @Override
    public void destroy() throws Exception {
        System.out.println("调用 DisposableBean.destroy() 方法");
    }

    /**
     * init-method 指定的初始化方法
     */
    public void init() {
        System.out.println("init-method 指定的初始化方法");
    }

    /**
     * destroy-method 指定的销毁方法
     */
    public void destroyMethod() {
        System.out.println("destroy-method 指定的销毁方法");
    }


    @Override
    public String toString() {
        return new StringJoiner(", ", User.class.getSimpleName() + "[", "]")
                .add("id=" + id)
                .add("name='" + name + "'")
                .add("age=" + age)
                .add("createTime=" + createTime)
                .toString();
    }
}
